package org.xhy.hrm.context;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.xhy.hrm.domain.LoginUser;

/**
 * 获取loginUser
 */
public class LoginUserContext {

    public static LoginUser getLoginUser() {
        //SecurityContextHolder.getContext拿到上下文
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null){
            return null;
        }
        //authentication就是相当于token
        Authentication authentication = context.getAuthentication();
        if (authentication == null){
            return null;
        }
        String principal = (String)authentication.getPrincipal();
        //字符串解析成对象
        LoginUser loginUser = JSON.parseObject(principal, LoginUser.class);
        return loginUser;
    }
}
